package com.cinco.blog.service.impl;

import com.cinco.blog.NotFoundException;
import com.cinco.blog.dao.TagDao;
import com.cinco.blog.po.Blog;
import com.cinco.blog.po.Tag;
import com.cinco.blog.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class TagServiceImpl implements TagService {
    @Autowired
    private TagDao tagDao;

    @Override
    public Tag saveTag(Tag tag) {
        return tagDao.save(tag);
    }

    @Override
    public Tag getTag(Long id) {
        return tagDao.getById(id);
    }

    @Override
    public Tag getTagByName(String name) {
        return tagDao.findByName(name);
    }
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagDao.findAll(pageable);
    }


    @Override
    public List<Tag> listTag() {
        return tagDao.findAll();
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);

        return tagDao.findTop(pageable);
    }

    @Override
    public List<Tag> listTag(String ids) {  //1,2,3
        return tagDao.findAllById(convertToList(ids));
    }

    private List<Long> convertToList(String ids) {      // 字符串转数组   {1,2,3} =>[1,2,3]
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null) {
            String[] idarray = ids.split(",");
            for (int i=0; i < idarray.length;i++) {
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagDao.getById(id);
        if (t == null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(tag,t);
        return tagDao.save(t);     //1、当添加的数据id为空时添加一条数据到数据库  2、当有id值时，修改数据库中的数据
    }

    @Override
    public void deleteTag(Long id) {
        tagDao.deleteById(id);
    }

}
